#include "threadhandle.h"

#include <QDebug>

ThreadHandle::ThreadHandle()
: QThread()
{
    m_adb = new UtilADB();
    connect(m_adb, &UtilADB::signal_adbCmdSync, this, &ThreadHandle::slot_adbCmdSync);
}

void ThreadHandle::run()
{
    m_running = true;
    E_ADB_RET ret = m_adb->PrepareADB(&m_adbCnt);
    if(ret != E_ADB_OK)
    {
        m_result = E_THREAD_RES_INTR;
    }
    else
    {
//        m_running = true;
        if(m_bCmdSync == true)
        {
            m_adb->CallADBSync(m_command);
            m_bCmdSync = false;
//            qDebug() << __func__ << "emit adbSyncEnd";
            emit(signal_adbSyncEnd());
        }
        else
        {
            m_adb->CallADB(m_command, m_cmdResult);
            if(m_cmdResult.contains("[OK]", Qt::CaseSensitive)){
                m_result = E_THREAD_RES_SUCCESS;
            } else if(m_cmdResult.contains("[NG]", Qt::CaseSensitive)) {
                m_result = E_THREAD_RES_FAIL;
            } else if(m_cmdResult.contains("[MODE]", Qt::CaseSensitive)) {
                m_result = E_THREAD_ERR_MODE;
            } else {
                m_result = E_THREAD_RES_OTHERS;
            }
        }
//        qDebug() << __FUNCTION__ << "exit";
//        m_running = false;
    }
    emit(signal_testReturn(m_adbCnt));
    m_running = false;
}

void ThreadHandle::setCommand(QString cmd)
{
    if(!cmd.isEmpty())
    {
        QString prefix = "shell ";
        m_command = prefix + cmd;
    }
    else
    {
        m_command = "";
    }
}

QString ThreadHandle::getCmdResult()
{
    return m_cmdResult;
}

ThreadResult ThreadHandle::getResult()
{
    return m_result;
}

void ThreadHandle::setCmdSync()
{
    m_bCmdSync = true;
}

void ThreadHandle::slot_adbCmdSync(QString strSync)
{
    emit(signal_testCmdSync(strSync));
}

bool ThreadHandle::isRunning()
{
    return m_running;
}
